package com.df.excel_export.export_java_demo;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public abstract class TbBaseContainer<T> {
    private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static final Lock readLock = readWriteLock.readLock();
    private static final Lock writelock = readWriteLock.writeLock();
    private ITb_Decode decoder;
    //配置列表
    private List<T> cfgs = new ArrayList<>();
    //配置映射
    private final HashMap<Integer, T> cfgMap = new HashMap<>();
    //最大id
    private Integer maxId;
    //最小id
    private Integer minId;
    //数据个数
    private Integer size;


    public TbBaseContainer(ITb_Decode decoder) {
        this.decoder = decoder;
    }

    public void loadData(){
        Lock writelock = getWritelock();
        writelock.lock();
        try {
            if(decoder==null){
                throw new RuntimeException("数据decoder未配置！容器名："+this.getClass().getName());
            }
            decoder.decode(this);
            //TODO 执行回调或发布事件

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            writelock.unlock();
        }
    }

    /**
     * 所有表数据加载后执行,不需要再次加锁
     * 一般是对自己表的数据再组装，不需要用到其他数据表
     */
    public abstract void onDataLoaded();


    /**
     * 获取数据表的名字，一般为序列化后的文件名
     * @return
     */
    public abstract String getTbName();





    public Lock getReadLock(){
        return readLock;
    }
    public Lock getWritelock(){
        return writelock;
    }

    public ITb_Decode getDecoder() {
        return decoder;
    }



    /**
     * 根据id获取配置
     * @param id
     * @return
     */
    public T getCfgById(Integer id){
        readLock.lock();
        try {
            return cfgMap.get(id);
        }finally {
            readLock.unlock();
        }
    }

    /**
     * 获取所有配置
     * @return
     */
    public List<T> getCfgs(){
        readLock.lock();
        try {
            return cfgs;
        }finally {
            readLock.unlock();
        }
    }

    /**
     * 获取所有配置
     * @return
     */
    public Integer getMaxId(){
        readLock.lock();
        try {
            return maxId;
        }finally {
            readLock.unlock();
        }
    }

    /**
     * 获取所有配置
     * @return
     */
    public Integer getMinId(){
        readLock.lock();
        try {
            return minId;
        }finally {
            readLock.unlock();
        }
    }


}
